use std::{env, fs};
use std::path::PathBuf;
use serde::Deserialize;
use crate::config::manager::SortBy;
use crate::config::MERGED_SPARROW;


#[derive(Debug,Deserialize)]
pub struct Manager {
    #[serde(skip)] 
    pub cwd: PathBuf , 
    #[serde(skip)] 
    pub cache : PathBuf , 
    
    // Sorting 
    pub sort_by : SortBy ,
    pub sort_reverse: bool , 
    
    // Display 
    pub show_hidden : bool , 
}

impl Manager {
    pub fn new() -> Self {
        #[derive(Deserialize)]
        struct Outer {
            manager : Manager ,
        }
        // 我们只取其中的manager子表
        let mut manager = toml::from_str::<Outer>(&MERGED_SPARROW)
            .unwrap_or_else(|err| panic!("Failed to parse TOML: {}", err))
            .manager;
        
        manager.cwd = env::current_dir().unwrap_or("/".into()) ;
        manager.cache = "/tmp/sparrow".into() ; // into是依靠rust自动推断的
        if !manager.cache.is_dir() { // 如果不存在这个文件夹那么重新创建一个
            fs::create_dir(&manager.cache).unwrap() ;
        }
        // use crate::inspect;
        // inspect!(manager);
        // Manager { cwd: "/Users/ys/work/sparrow", cache: "/tmp/sparrow", sort_by: Modified, sort_reverse: true, show_hidden: false }
        manager
    }
}